#include <libcomm.h>

void __SignalHandler(int signo) 
{
	printf("SIGNAL(%d) interrupt !\n",signo);
	printf("%s",StackTracer::TraceStack().get());
	exit(0);
}
RPC* g_rpc = NULL;
class MyClass
{
public:
	MyClass()
	{
		RPC_FUNC_REGISTER(MyClass,GetName,String,int);
		RPC_FUNC_REGISTER(MyClass,Error,int);
	}
	String GetName(int index)
	{
		const char* szNames[] = {"hello","world","bye"};
		CommType response;
		g_rpc->Call("MyClass::Error",Arguments(),&response);
		return szNames[index];
		
	}
	int Error()
	{
		printf("error index!\n");
		return 2;
	}
};

#define CRT_FILE	"d:\\mycrt\\www.wanghonghao.cn.pem"
#define KEY_FILE	"d:\\mycrt\\www.wanghonghao.cn.key"

int main(int argc, char *argv[])
{
#ifndef COMM_MSVC
	struct sigaction act;
	act.sa_handler = __SignalHandler;
	MYLIB_ASSERT_ERRNO(0==sigfillset(&act.sa_mask));//forbid all signal while handler.
	act.sa_flags = 0;
	//MYLIB_ASSERT_ERRNO(0==sigaction(SIGINT,&act,NULL));
	MYLIB_ASSERT_ERRNO(0==sigaction(SIGSEGV,&act,NULL));
	MYLIB_ASSERT_ERRNO(0==sigaction(SIGILL,&act,NULL));
	MYLIB_ASSERT_ERRNO(0==sigaction(SIGFPE,&act,NULL));
	MYLIB_ASSERT_ERRNO(0==sigaction(SIGTERM,&act,NULL));
	MYLIB_ASSERT_ERRNO(0==sigaction(SIGABRT,&act,NULL));
	//signal(SIGUSR1,SIG_IGN);
#endif

	LOGDEBUG("COMLIB: %s",common_version());

	CommTime now = Timer::Now();
	printf("%04d-%02d-%02d(%d) %02d:%02d:%02d:%06d\n",now.year,now.month,now.day,now.wday,now.hour,now.minute,now.second,now.microsecond);

	SocketAddress address(40218,"127.0.0.1");
#ifdef __GNUC__
	//SocketAddress address(String::format("%s/server.sock",Application::GetApplicationDirectory().get()));
#endif
	String input(512);
	MyClass clsInst;
	RPC rpc(address,(argc==1)?false:true,ThreadPool::DefaultThreadsCount,10/*,CRT_FILE,KEY_FILE*/);
	g_rpc = &rpc;
	do 
	{
		gets(input);
		if(input == "")
		{
			continue;
		}
		if(input == "q")
		{
			break;
		}
		else if(input == "c")
		{
			rpc.Messager()->Peer()->Close();
			//break;
			continue;
		}
		
		int index = atoi(input);
		if(index >= 1 && index <=3)
		{
			CommType result;
			Arguments args;
			args << index-1;
			if(rpc.Call("MyClass::GetName",args,&result))
			{
				printf("rpc class result: %s.\n",(const char*)result);
			}
		}
		else
		{
			rpc.Call("MyClass::Error");
		}

	} while (true);
	
	return 0;
}